package com.ruoyi.shop.common.utils;

import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 商城工具类
 * 
 * @author ecpex
 *
 */
public class ShopUtils {

	/**
	 * 逗号分隔处理
	 * 
	 * @param str
	 * @return
	 */
	public static String comma(String str) {
		if (str == null) {
			return "";
		}
		str = str.replace("，", ","); // 中文逗号转换
		str = StringUtils.deleteWhitespace(str);// 去除空格
		return str;
	}

	/**
	 * 获取绝对路径
	 * 
	 * @param url
	 * @return
	 */
	public static String getAbsoluteUrl(String url) {
		if (StringUtils.isEmpty(url)) {
			return StringUtils.EMPTY;
		}
		if (url.startsWith(Constants.RESOURCE_PREFIX) || url.startsWith("/img")) {
			return getDomain() + url;
		}
		return url;
	}

	/**
	 * url集合替换
	 * 
	 * @param urls
	 * @return
	 */
	public static String getAbsoluteUrls(String urls) {
		String[] values = urls.split(",");
		String comma = "";
		StringBuilder result = new StringBuilder();
		for (String value : values) {
			result = result.append(comma).append(getAbsoluteUrl(value));
			comma = ",";
		}
		return result.toString();
	}

	/**
	 * 获取域名
	 * 
	 * @param request
	 * @return
	 */
	public static String getDomain() {
		HttpServletRequest request = ServletUtils.getRequest();
		StringBuffer url = request.getRequestURL();
		String contextPath = request.getServletContext().getContextPath();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
	}

	/**
	 * 随机数
	 * 
	 * @param length
	 * @return
	 */
	public static String randomInt(int length) {
		Random random = new Random();
		StringBuilder stringBuffer = new StringBuilder();
		String str = "0123456789";
		for (int i = 0; i < length; i++) {
			int index = random.nextInt(10);
			stringBuffer.append(str.charAt(index));
		}
		return stringBuffer.toString();
	}

}
